import React, { useState, useEffect } from "react";
import { fetchItems } from "@/api/item";
import type { Item } from "./types";
import { Table, Tooltip, Tag, Switch, Image, Button, Upload } from "antd";
import { DownloadOutlined  } from '@ant-design/icons'
import SearchBar from "@/components/SearchBar";
import './style.scss'
import { utils, writeFile, read } from "xlsx";
import { useNavigate } from "react-router-dom";
export default function ItemLists() {
  const navigate = useNavigate();
  const [total, setTotal] = useState(0);
  const [items, setItems] = useState<Item[]>([]);
  let page = 1;
  let pageSize = 10;
  let searchParams: {keyWords?: string,start?:string,end?: string} = {
    keyWords: '',
    start: '',
    end: ''
  }
  // 点击搜索
  const onSearch = (params: {keyWords?: string,start?:string,end?: string}) => {
    searchParams = params
    getItems()
  }
  // 点击切换分页 当前页 和 一页多少条
  const paginationChange = (_page: number, _pageSize: number) => {
    page = _page;
    pageSize = _pageSize;
    getItems()
  }
  const getItems = () => {
    fetchItems({
      ...searchParams,
      page,
      pageSize
    }).then((res) => {
      if (res.data.code === 200) {
        setItems(res.data.data.lists);
        setTotal(res.data.data.total)
      }
    });
  };

  useEffect(() => {
    getItems();
  }, []);
  const [visible, setVisible] = useState(false);
  const columns = [
    {
      title: "商品名",
      dataIndex: "itemName",
      key: "itemName",
    },
    {
      title: "描述",
      dataIndex: "desc",
      render: (desc: string) => {
        return (
          <Tooltip placement="bottom" title={desc}>
            <span>{desc.substring(0, 15)}...</span>
          </Tooltip>
        );
      },
      key: "desc",
    },
    {
      title: "价格",
      dataIndex: "price",
      key: "price",
    },
    {
      title: "销量",
      dataIndex: "sale",
      render: (sale: number) => {
        return <Tag color={sale > 500 ? "red" : "green"}>{sale}</Tag>;
      },
      key: "sale",
    },
    {
      title: "上下架",
      dataIndex: "onsale",
      render(onsale: number) {
        return (
          <Switch
            checkedChildren="上架"
            unCheckedChildren="下架"
            defaultChecked={onsale === 1}
            onChange={(checked: boolean) => {
              console.log(checked);
            }}
          />
        );
      },
      key: "onsale",
    },
    {
      title: "封面",
      dataIndex: "thumb",
      render(thumb: string, row: Item){
        return (
          <>
            <Image
              preview={{ visible: false, maskClassName: 'mask' }}
              width={100}
              src={row.pics[0].url}
              onClick={() => setVisible(true)}
            />
            <div style={{ display: 'none' }}>
              <Image.PreviewGroup preview={{ visible, onVisibleChange: (vis) => setVisible(vis) }}>
                {
                  row.pics.map((pic) => (
                    <Image key={pic.id} src={pic.url} />
                  ))
                }
                
               
              </Image.PreviewGroup>
            </div>
          </>
         
        )
      },
      key: "thumb",
    },
    {
      title: "上架时间",
      dataIndex: "createAt",
      key: "createAt",
    },
    {
      title: "操作",
      render(row:any){
        return (
          <>
            <Button type="primary" danger size="small">删除</Button>
            <Button onClick={
              () => {
                // 跳转到 修改商品页
                navigate(`/itemUpdate?itemId=${row.id}`)
              }
            } type="primary"  size="small">编辑</Button>
          </>
        )
      },
      key: "action",
    }
  ];
  
  // 导出excel模板
  const exportXlsx  =() => {
    // 导出数据
    const data = [
      {
        商品名: '商品n',
        价格: 10,
        描述: '这是描述'
      }
    ]
    const ws = utils.json_to_sheet(data);
    const wb = utils.book_new();
    utils.book_append_sheet(wb, ws, "Data");
    writeFile(wb, "商品.xlsx");
  }
  // 选择本地的 excel文件 批量上传
  const uploadXlsx = (file: any) => {
    const fd = new FileReader();
    fd.readAsArrayBuffer(file)
    fd.onload = () => {
      const wb = read(fd.result); // parse the array buffer
      const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
      const data = utils.sheet_to_json(ws)
      const items = data.map((item: any) => {
        return {
          itemName: item.商品名,
          price: item.价格,
          desc: item.描述
        }
      })
      // 发送请求 请求 批量 新增商品接口
      
    }
    return false
  }
  return (
    <>
       {/* 搜索 */}
      <SearchBar onSearch={onSearch}/>
      <div className="action-btns">
        <Button type="primary" onClick={
          () => {
            navigate('/itemAdd')
          }
        }>单个新增</Button>
        <Upload
          action="#"
          accept=".xls, .xlsx"
          showUploadList={false}
          beforeUpload={
            uploadXlsx
          }
        >
          <Button type="primary" style={{margin: '0 10px', background:'#E43D30'}}>批量新增</Button>
        </Upload>
        <Button type="link" icon={<DownloadOutlined/>} onClick={
          exportXlsx
        }>
         导出模板
        </Button>
      </div>
      <Table 
        columns={columns}
        dataSource={items}
        pagination = {
          {
            defaultCurrent: page,
            defaultPageSize: pageSize,
            total: total,
            onChange: paginationChange
          }
        }
        rowKey="id" />
    </>
  );
}
